<script setup lang="ts">
import type { CellValueChangedEvent } from 'ag-grid-community'

import { reactive, ref, watch } from 'vue'

import { AgGridVue } from 'ag-grid-vue3'

import rightColumnActionsRenderer from '#/views/backend/spuBom/components/agGridVueComponents/rightColumnActionsRenderer.vue'

import { stop } from './state'

import 'ag-grid-enterprise'

import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-quartz.css'

const materialGridRef = ref()
const props = defineProps<{
  modelValue: any[] // 父组件 v-model 传入
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', payload: any[]): void
}>()

const materialData = ref([])

// 含损耗用量-计算器
const onSinglePieceCompute = (params: any) => {
  const { field } = params.colDef
  params.data[field] = params.newValue
  const net_single_piece = params.data.net_single_piece || 0
  const loss = params.data.loss || 0
  params.data.single_piece = Number((net_single_piece * (1 + loss / 100)).toFixed(6))
}

watch(
  () => props.modelValue,
  (val) => {
    materialData.value = props.modelValue
  },
  { immediate: true },
)

function syncBack() {
  emit('update:modelValue', materialData.value)
}

const materialGridOptions: any = reactive({
  components: { rightColumnActionsRenderer },
  columnDefs: [
    {
      headerName: '大类',
      field: 'bom_type',
      editable: true,
      cellEditor: 'agSelectCellEditor',
      cellEditorParams: {
        values: ['面料', '辅料', '包装辅料'],
      },
      width: 150,
      rowDrag: true,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
    },
    {
      headerName: 'bom简称',
      field: 'bom_name',
      editable: true,
      cellClass: 'borderCcc',
      // cellEditor: 'ElDateEditorComponent',
      // cellEditorPopup: true // 推荐弹出式编辑器
      suppressMenu: true, // 仅此列不显示菜单按钮
      width: 200,
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '净用量',
      field: 'net_single_piece',
      editable: true,
      cellDataType: 'number',
      width: 100,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      valueSetter: onSinglePieceCompute,
    },
    {
      headerName: '核算单价',
      field: 'price',
      editable: true,
      cellDataType: 'number',
      width: 150,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '操作',
      cellClass: 'borderCcc',
      editable: false,
      suppressMenu: true, // 仅此列不显示菜单按钮
      field: 'actions',
      pinned: 'right', // 固定在右侧

      cellRenderer: 'rightColumnActionsRenderer', // 使用自定义渲染组件
      cellRendererParams: {
        context: {
          buttons: ['del'],
          deleteRow: (index) => {
            // 传递删除方法到渲染器
            const pData = [...materialData.value]
            pData.splice(index, 1)
            materialData.value =pData
            syncBack()
            stop.value = !stop.value
          },
        },
      },
    },
  ],
  rowData: [],
  // height: '500px', // 设置整个表格的高度为400px
  domLayout: 'autoHeight', // 设置表格自适应高度
  rowHeight: 30, // 设置全局行高为50px
  enableRangeSelection: true,
  enableFillHandle: true, // 开启拖动复制
  suppressClearOnFillReduction: false, // 可选：控制填充行为
  defaultColDef: {
    editable: true, // 必须设置为可编辑，否则无法复制
  },
  suppressClickEdit: false, // 禁用单击即编辑
  rowDragManaged: true, // 启用托管拖拽
  editType: 'cellEditor', // fullRow,cellEditor
  getContextMenuItems: (params: any) => {
    const result = [
      'export',
      {
        name: '向上插入一行',
        action: () => {
          const newRow = { id: 0, bom_type: '面料' }
          const selectedNode = params.node
          const mData = [...materialData.value]
          const startIndex = selectedNode ? Math.max(selectedNode.rowIndex, 0) : 0
          mData.splice(startIndex, 0, newRow)
          materialData.value = mData
        },
      },
      {
        name: '向下插入一行',
        action: () => {
          const newRow: any = { id: 0, bom_type: '面料' }
          const selectedNode = params.node
          const mData = [...materialData.value]
          // let indexConfig = selectedNode?{ addIndex: (selectedNode.rowIndex + 1)}:{};
          // params.api.applyTransaction({ add: [newRow],...indexConfig})

          const startIndex = selectedNode ? selectedNode.rowIndex + 1 : 0
          mData.splice(startIndex, 0, newRow)
          materialData.value = mData
        },
      },
      {
        name: '删除选中行',
        action: () => {
          const getCellRanges = params.api.getCellRanges()[0]
          const infoStartRow = getCellRanges.startRow.rowIndex
          const infoEndRow = getCellRanges.endRow.rowIndex
          const startRow = Math.max(infoEndRow, infoStartRow)
          const endRow = Math.min(infoEndRow, infoStartRow)
          const pData = [...materialData.value]
          for (let i = startRow; i >= endRow; i--) {
            pData.splice(i, 1)
          }
          materialData.value = pData
          syncBack()
        },
      },
    ]
    return result
  },
  onRowDragEnd: (event: any) => {
    const newOrder: any = []
    event.api.forEachNode((node: any) => {
      newOrder.push(node.data)
    })
    materialData.value = newOrder // 更新响应式数组
  },
  onCellValueChanged: (params: CellValueChangedEvent) => {
    const rowIndex: any = params.rowIndex
    const field: any = params.colDef.field
    const newValue: any = params.newValue
    // 更新响应式数据
    const updated: any = [...materialData.value]
    updated[rowIndex] = {
      ...updated[rowIndex],
      [field]: newValue,
    }
    materialData.value = updated
    syncBack()
    // emit('update:data', materialData.value);
  },
})


watch(
  () => stop.value, (val) => {
    materialGridRef.value?.api?.stopEditing()
  },
  { immediate: false },
)
</script>

<template>
  <div>
    <AgGridVue ref="materialGridRef" :row-data="materialData" :grid-options="materialGridOptions" class="ag-theme-quartz" style="width: 800px; flex-grow: 1; overflow-y: scroll" borderd />
  </div>
</template>

<style lang="scss" scoped>
:deep(.borderCcc) {
  // 表体单元格右边框
  border-right: 1px solid #ccc;
}
:deep(.ag-cell, .ag-full-width-row .ag-cell-wrapper.ag-row-group) {
  // 表体左右内边距
  padding: 0;
}

:deep(
//.ag-theme-balham .ag-header-cell-label,
//.ag-theme-alpine .ag-header-cell-label,
.ag-theme-quartz .ag-header-cell-label) {
  // 表头标题居中
  justify-content: center;
  display: flex;
  align-items: center;
}
:deep(.ag-header-cell, .ag-header-group-cell) {
  // 表头左右内边距
  padding: 0;
}
:deep(.ag-ltr .ag-header-viewport .ag-header-cell-resize::after) {
  // 表头右边框
  left: calc(50% - 0px);
}
:deep(.ag-header-cell-resize::after) {
  // 表头右边框
  width: 1px;
  height: 100%;
  top: 0;
}
</style>
